package com.beyond.core.handler;

import java.util.concurrent.ExecutorService;

import com.beyond.core.service.ProtocolService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServerHandler extends 
SimpleChannelInboundHandler<DatagramPacket> {	
	
	private ExecutorService ex;
	public NettyServerHandler(ExecutorService ex) {	
		this.ex  = ex;
	}
	
	@Override 
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 
        ctx.flush();         
    }
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		
		  String channelIdstr = ctx.channel().id().asLongText();			
		   cause.printStackTrace();
		  log.debug(channelIdstr+"通道异常捕获");		  
	      ctx.close();
	}	
 
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        
		//String req=packet.content().toString(CharsetUtil.UTF_8);
		final ByteBuf buf = packet.content();
		int readableBytes = buf.readableBytes();
		byte[] content = new byte[readableBytes];
		buf.readBytes(content);
		
        String hostName = packet.sender().getHostName();
        String hostAddress = packet.sender().getAddress().getHostAddress();
        int port = packet.sender().getPort();
        log.info("hostName="+hostName+"address="+hostAddress+"port="+port);

        this.ex.execute(new ProtocolService(ctx, hostAddress,port,content));       
		/*
		 * if("hello".equals(req)){ //创建新的DatagramPacket对象，传入返回消息和目的地址（IP和端口）
		 * ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
		 * "world=>",CharsetUtil.UTF_8), packet.sender())); }
		 */
	}
	
}
